<template>
  <div class="app-container">
    <div style="display: flex;justify-content: space-around; margin-bottom: 20px;">
    <div class="echart" id="mychart" :style="myChartStyle"></div>
    <div class="echart" id="monthchart" :style="myChartStyle"></div>
    </div>

    <div>
      <div style="display: flex;">
      <div>近期订单</div>
      <div style="margin-left: auto;">
        <el-button size="medium"
                type="text"
                @click="jumpBillsList()">更多>></el-button>
              </div>
            </div>
      <el-card>
        <el-table :data="paymentList">
          <el-table-column label="订单编号" align="center" prop="billInfoId" />
          <el-table-column label="月份" align="center"  prop="billDate" />
          <el-table-column label="金额" align="center"  prop="payAmounts" />
          <el-table-column label="报告详情" align="center">
            <template slot-scope="scope">
            <el-button
                size="mini"
                type="text"
                @click="jumpReportDetail(scope.row.billInfoId)"

              >报告详情</el-button>
          </template>
        </el-table-column>
          <el-table-column label="支付状态" align="center" >
              <template slot-scope="scope">
              <el-button v-if="scope.row.payMethod" type="success" @click="jumpBillsDetail(scope.row.billInfoId)">已支付</el-button>
              <el-button v-else type="danger" @click="jumpBillsDetail(scope.row.billInfoId)">未支付</el-button>
            </template>
          </el-table-column>
        </el-table>
      </el-card>
    </div>
    <div class="main-content">
      <!-- 其他内容 -->

      <!-- 放置广告窗 -->
      <div class="ad-container" v-if="showAd">
      <AdWindow v-if="showAd" @close="closeAdWindow" />
    </div>
    </div>
  </div>


</template>

<script>
import {  getDayElecInfo,getMonthElecInfo  } from "@/api/system/dayElecInfo";
import {  getBillList  } from "@/api/system/bill";
import { getUserProfile } from "@/api/system/user";
import * as echarts from "echarts";
import AdWindow from "@/views/system/dayElecInfo/AdWindow.vue" // 引入广告窗组件
export default {
  name: "DayElecInfo",
  components:{
    AdWindow
  },
  data() {
    return {
      showAd: true, // 控制是否显示广告窗
      showDayChart: true,
      showMonChart: false,
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 每日用电情况表格数据
      list:[],
      dayElecInfoList: [],
      dayElec:[],
      //每月用电情况表格数据
      monthElecInfoList: [],
      monthElec:[],
      monthElecYear:[],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        eUsage: null,
        eTime: null
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
      },
      // 折线图
      myChart: {},
      monthChart: {},
      xData: [], //横坐标
      yData: [], //电量数据
      myChartStyle: { flex: 1, height: '400px', marginRight: '20px' } ,//图表样式
      monthChartStyle: { flex: 1, height: '400px'  } ,//图表样式
     //账单表格
      paymentList: null,
      month:[],
      // 账单状态
      ispaid: false,
      userId: null,

    };
  },
  mounted() {
    this.getList();
  },
  // created() {
  //   this.getList();
  // },
  methods: {
    closeAdWindow() {
      this.showAd = false; // 关闭广告窗
    },
    /*每日图表的初始化*/
    initDayEcharts() {
      const xData = this.dayElec;
      const yData = this.dayElecInfoList;
      const option = {
        title: {
          text: '近七日用电情况',
          left: 'center',
          top: '3%' // 向下移动标题
      },
        xAxis: {
          data: xData
        },
        yAxis: {},
        series: [
          {
            data: yData,
            type: "line" // 类型设置为折线图
          }
        ]
      };
      this.myChart = echarts.init(document.getElementById("mychart"));
      this.myChart.setOption(option);
      //随着屏幕大小调节图表
      window.addEventListener("resize", () => {
        this.myChart.resize();
      });
    },
     /*每月图表的初始化*/
     initMonthEcharts() {
      const xData = this.monthElec;
      const yData = this.monthElecInfoList;
      const option = {
        title: {
          text: '近一个月用电情况',
          top: '3%', // 向下移动标题
          left: 'center'
      },
        xAxis: {
          data: xData
        },
        yAxis: {},
        series: [
          {
            data: yData,
            type: "line" // 类型设置为折线图
          }
        ]
      };
      this.monthChart = echarts.init(document.getElementById("monthchart"));
      this.monthChart.setOption(option);
      //随着屏幕大小调节图表
      window.addEventListener("resize", () => {
        this.monthChart.resize();
      });
    },
    /** 查询用电情况列表 */
    getList() {
      getUserProfile().then(response => {
        if(this.$route.params.userId)
        {
          this.userId = this.$route.params.userId;
          console.log(this.userId);

            }else{

         this.userId = response.data.userId;

        }

        this.getElecData(this.userId);
      })
    },
    // 获取用电数据
    getElecData(userId){
      getDayElecInfo(userId).then(response => {

      this.list = response;
      this.list.forEach(item => {
        this.dayElecInfoList.push(item.totalUsage);
        this.dayElec.push(this.extractDate(item.elecDate))
      })
      this.initDayEcharts();
      this.total = response.total;
      this.loading = false;
      });
      getMonthElecInfo(userId).then(response => {

      this.list = response;
      this.list.forEach(item => {
        this.monthElecInfoList.push(item.totalUsage);
        this.monthElec.push(item.week)
        this.monthElecYear.push(item.year)
      })
      var lastIndex = this.monthElec.length - 1;

      // 更改最后一个元素的值
      this.monthElec[lastIndex] = '本周';
      this.initMonthEcharts();
      this.total = response.total;
      this.loading = false;

      });
      getBillList(userId).then(response => {

      this.paymentList = response;
      this.paymentList.forEach(item => {
      const monthMatch = item.billDate.match(/^(\d{4}-\d{2})/); // 匹配'-'后跟随两个数字再跟随'-'的部分
      if (monthMatch) {
        item.billDate = monthMatch[1]; // 获取匹配到的数字部分

      }

      })


      });

    },
    extractDate(timestamp) {
    // 使用正则表达式匹配日期部分
    const dateMatch = timestamp.match(/(\d{4})-(\d{2})-(\d{2})/);

    // 如果匹配成功，则提取月份和日期并返回它们
    if (dateMatch) {
        return `${dateMatch[2]}-${dateMatch[3]}`;
    }

    // 如果没有匹配到日期，则返回 null 或其他默认值
    return null;
},
// 跳转账单详情
    jumpBillsDetail:function(id){
      const payId = id;

      this.$router.push({path:"/system/billsDetail/ele-billsdetail/" + payId,query:{id:payId}});
    },
    //跳转账单列表
    jumpBillsList: function(){

          this.$router.push({path:"/system/billsList/ele-billsList/" + this.userId,query:{ id:this.userId}});
        },
        //跳转报告详情
    jumpReportDetail: function(id){

      const billInfoId =  id;
      this.$router.push({path:"/system/reportDetail/ele-report/" + billInfoId,query:{id:billInfoId}}).catch(err => {
        this.$message("跳转失败")
      });

    },

}};
</script>
<style>
body {
  overflow: hidden;
}

.main-content {
  position: relative;
  height: 100vh;
}

.app-container {
  display: flex;
  flex-direction: column;
  height: 100vh;
}
.ad-container {
  position: absolute;
  bottom: 0px; /* 距离底部20px */
  right: 0px; /* 距离右边20px */
  /* 如果AdWindow有固定宽度，你也可以在这里设置它 */
}
.echart {
  width: 100%;
  max-width: 600px;
  margin-bottom: 20px;
  height: 300px;
  box-shadow: 0 2px 12px rgba(0,0,0,0.2);
}

</style>
